Apple 的 Cocoa 函式庫對於 Objective-C 的 Error Handling 有固定的編寫方式,可以參考 Introduction to Error Handling Programming Guide For Cocoa
而 Swift語言在對接 Objective-C 有預設的直接對接方式
NSError**,且
關於 Cocoa Error Parameters 可以參考:
About Imported Cocoa Error Parameters - Apple Developer Documentation
// Objective-C
@interface Atemplate : NSObject
- (BOOL) canFailureMethodForURL: (NSURL*) aURL WithError:(NSError**)aError NS_SWIFT_NOTHROW;
@end
使得 Swift interface 就是直接對照到 Method。
Swift 語言的 Error handling 對於指令的錯誤有所謂的錯誤回饋,對於 C 語言也是有同樣的方法。在 C 語言中,我們常見到的 malloc、fopen 在無法取得正確 return 的時候,會回傳 NULL,而透過 errno.h則可以取得相對應的錯誤資訊。
// C
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main () {
   FILE * pf;
   int errnum;
   pf = fopen ("unexist.txt", "rb");
	
   if (pf == NULL) {
   
      errnum = errno;
      fprintf(stderr, "Value of errno: %d\n", errno);
      perror("Error printed by perror");
      fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
   } else {
      fclose (pf);
   }
   
   return 0;
}
/*
 * Value of errno: 2
 * Error printed by perror: No such file or directory
 * Error opening file: No such file or directory
*/
範例來自於 tutorialspoint.com
errno.h 套用 Error handling?